package ru.paswd.marketprice.storage.receipt.app.services;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.paswd.marketprice.storage.receipt.app.entity.Receipt;
import ru.paswd.marketprice.storage.receipt.app.entity.ReceiptItem;
import ru.paswd.marketprice.storage.receipt.app.repositories.ReceiptItemsRepository;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ReceiptItemService {
    private final ReceiptItemsRepository receiptItemsRepository;
    private final ReceiptService receiptService;

    @Transactional
    public void addItem(String fiscalNumber, String fiscalSign, String fiscalDocumentNumber, ReceiptItem receiptItem) {
        Receipt receipt = receiptService.getReceiptByParams(fiscalNumber, fiscalSign, fiscalDocumentNumber);
        receiptItem.setReceipt(receipt);
        receiptItemsRepository.save(receiptItem);
    }

    @Transactional
    public void removeItem(String fiscalNumber, String fiscalSign, String fiscalDocumentNumber, String name) {
        Receipt receipt = receiptService.getReceiptByParams(fiscalNumber, fiscalSign, fiscalDocumentNumber);
        if (name != null && !name.isEmpty())
            receiptItemsRepository.deleteAllByReceiptAndName(receipt, name);
        else
            receiptItemsRepository.deleteAllByReceipt(receipt);
    }
}
